<template>
   <div>
      <el-breadcrumb separator="/">
         <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item><a href="javascript:;">商品分类</a></el-breadcrumb-item>
         <el-breadcrumb-item>分类列表</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="hengxian"></div>

      <el-row>
         <el-col :span="15">
            <el-button type="primary" size="mini" @click="dialogTableCreate = true">
               <i class="el-icon-plus"></i><span>新增</span>
            </el-button>
         </el-col>

         <el-col :span="5">
            <div>
               <el-input placeholder="请输入内容" v-model="keyword" class="input-with-select" size="mini">
                  <el-select v-model="cate" slot="prepend" placeholder="请选择">
                     <el-option label="顶级分类ID" value="id"></el-option>
                     <el-option label="顶级分类名称" value="name"></el-option>
                  </el-select>
                  <el-button slot="append" @click="handleSearch" icon="el-icon-search"></el-button>
               </el-input>
            </div>
         </el-col>
      </el-row>

      <el-table :data="categories" style="width: 100%;margin-bottom: 20px;" row-key="id" border
                default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
         <el-table-column label="ID" prop="id" width="90"></el-table-column>
         <el-table-column label="缩略图" prop="image">
            <template slot-scope="scope">
               <img v-if="scope.row.image" :src="scope.row.image" alt="" @click="handleShow(scope.$index,scope.row)"
                    class="image">
            </template>
         </el-table-column>
         <el-table-column label="名称" prop="name">
            <template slot-scope="scope">
               <el-tag v-if="scope.row.parent_id == 0">{{scope.row.name}}</el-tag>
               <div v-else>|———— {{scope.row.name}} &nbsp;&nbsp;
                  <router-link :to="{name:'products',params:{category_id:scope.row.id}}">
                     <el-button v-if="scope.row.products != ''" type="success" size="mini">查看</el-button>
                  </router-link>
               </div>
            </template>
         </el-table-column>
         <el-table-column prop="is_show" label="是否显示" width="80">
            <template slot-scope="scope">
               <i :class="scope.row.is_show ? 'el-icon-success' : 'el-icon-error'"
                  @click="handleChangeAttr(scope.row)"></i>
            </template>
         </el-table-column>
         <el-table-column label="排序" prop="sort_order">
            <template slot-scope="scope">
               <el-input-number v-model="scope.row.sort_order"
                                @change="handleChange(scope.row.id,scope.row.sort_order)"
                                :min="1" :max="999" size="mini"></el-input-number>
            </template>
         </el-table-column>
         <el-table-column label="分类描述" prop="description"></el-table-column>
         <el-table-column label="操作">
            <template slot-scope="scope">
               <i class="el-icon-edit" @click="handleEdit(scope.$index,scope.row)"></i>
               <i class="el-icon-delete" @click="handleDelete(scope.$index,scope.row)"></i>
            </template>
         </el-table-column>
      </el-table>

      <!--查看大图-->
      <el-dialog :visible.sync="showImg" :width="width" custom-class="an-img-dialog" :center="true">
         <img :src="category.image" alt="" @load="onLoad">
      </el-dialog>

      <!--新增分类模态框-->
      <el-dialog title="新增分类" :visible.sync="dialogTableCreate" @close='closeDialog'>
         <el-form :model="category" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="上级分类" prop="parent_id">
               <el-select v-model="category.parent_id" placeholder="请选择">
                  <el-option :value="0" label="顶级分类"></el-option>
                  <el-option v-for="item in categories" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
               <el-input v-model="category.name"></el-input>
            </el-form-item>
            <el-form-item label="缩略图" prop="image">
               <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                  <img v-if="category.image" :src="category.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
            </el-form-item>
            <el-form-item label="是否显示" prop="is_show">
               <el-switch v-model="category.is_show"></el-switch>
            </el-form-item>
            <el-form-item label="排序" prop="sort_order">
               <el-input-number v-model="category.sort_order" @change="handleCreateChange" :min="1"
                                :max="999"></el-input-number>
            </el-form-item>
            <el-form-item label="描述" prop="description">
               <el-input type="textarea" v-model="category.description"></el-input>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" size="mini" @click="submitForm('ruleForm')">保存</el-button>
               <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
         </el-form>
      </el-dialog>

      <!--编辑分类-->
      <el-dialog title="编辑分类" :visible.sync="dialogTableEdit" @close='closeDialog'>
         <el-form :model="category" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="上级分类" prop="parent_id">
               <el-select v-model="category.parent_id" placeholder="请选择">
                  <el-option :value="0" label="顶级分类"></el-option>
                  <el-option v-for="item in categories" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
               <el-input v-model="category.name"></el-input>
            </el-form-item>
            <el-form-item label="缩略图" prop="image">
               <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                  <img v-if="category.image" :src="category.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
            </el-form-item>
            <el-form-item label="是否显示" prop="is_show">
               <el-switch v-model="category.is_show"></el-switch>
            </el-form-item>
            <el-form-item label="排序" prop="sort_order">
               <el-input-number v-model="category.sort_order" @change="handleCreateChange" :min="1"
                                :max="999"></el-input-number>
            </el-form-item>
            <el-form-item label="描述" prop="description">
               <el-input type="textarea" v-model="category.description"></el-input>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" size="mini" @click="updateForm('ruleForm')">更新</el-button>
               <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
         </el-form>
      </el-dialog>

   </div>
</template>

<script>
   export default {
      name: "Home",
      data() {
         return {
            loading: false,
            showImg: false,
            width:'',
            keyword: '',
            cate: '',
            categories: [],
            dialogTableCreate: false,
            category: {
               parent_id: '',
               name: '',
               image: '',
               is_show: true,
               sort_order: 999,
               description: ''
            },
            rules: {
               parent_id: [
                  {required: true, message: '请选择上级分类', trigger: 'change'}
               ],
               name: [
                  {required: true, message: '请输入分类名称', trigger: 'blur'},
                  {min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
               ],
            },
            dialogTableEdit: false,
         }
      },

      created() {
         this.init();
      },
      methods: {
         onLoad(e){
            const img = e.target;
            let width = 0;
            if (img.fileSize > 0 || (img.width > 1 && img.height > 1)) {
               width = img.width + 40;
            }
            this.width = width + 'px';
         },
         //搜索
         handleSearch() {
            this.init();
         },
         //查看大图
         handleShow(index, row) {
            this.category.image = row.image;
            this.showImg = true;
         },
         //改变排序
         handleCreateChange(value) {
            this.category.sort_order = value;
         },
         //首页
         init() {
            this.loading = true;
            axios.get(`/admin/shop/categories?cate=${this.cate}&keyword=${this.keyword}`)
               .then((res) => {
                  // console.log(res.data);
                  this.categories = res.data;
                  this.loading = false;
               })
         },
         //改变属性
         handleChangeAttr(row) {
            axios.patch(`/admin/shop/categories/change_attr`, {id: row.id, is_show: row.is_show})
               .then((res) => {
                  this.$notify({
                     title: '成功',
                     message: '改变状态成功',
                     type: 'success'
                  });
                  this.init();
               })
         },
         //排序
         handleChange(id, sort_order) {
            axios.patch(`/admin/shop/categories/change_sort`, {id: id, sort_order: sort_order})
               .then((res) => {
                  this.$notify({
                     title: '成功',
                     message: '排序成功！',
                     type: 'success',
                  });
                  this.init();
               })
         },
         //删除
         handleDelete(index, row) {
            this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning',
               center: true
            }).then(() => {
               axios.delete(`/admin/shop/categories/${row.id}`)
                  .then((res) => {
                     // console.log(res);
                     if (res.data.status == 1) {
                        this.categories.splice(index, 1);
                        this.$message({
                           type: 'success',
                           message: res.data.msg,
                        });
                        this.init();
                     } else {
                        this.$message.error(res.data.msg);
                     }
                  });
            }).catch(() => {
               this.$message({
                  type: 'info',
                  message: '已取消删除'
               });
            });
         },
         //图片上传
         handleAvatarSuccess(res, file) {
            this.category.image = res.msg;
         },
         beforeAvatarUpload(file) {
            // const isJPG = file.type === 'image/jpeg';
            const img = ['image/jpeg', 'image/png', 'image/gif'];
            const isJPG = img.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
               this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
            }
            if (!isLt2M) {
               this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
         },
         //关闭模态框,先清空验证再清楚表单
         closeDialog() {
            this.$refs.ruleForm.clearValidate();
            this.$refs.ruleForm.resetFields();
            this.category = {};  //清空表单值
         },
         //新增
         submitForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  axios.post(`/admin/shop/categories`, this.category)
                     .then((res) => {
                        if (res.data.status == 1) {
                           this.$message({
                              showClose: true,
                              message: res.data.msg,
                              type: 'success'
                           });
                           this.dialogTableCreate = false;
                           this.init();
                           this.$refs[formName].resetFields();  //重置表单
                        } else {
                           this.$message.error(res.data.msg);
                        }
                     })
               } else {
                  this.$message({
                     showClose: true,
                     message: '新增分类失败',
                     type: 'error'
                  });
                  return false;
               }
            });
         },
         resetForm(formName) {
            this.$refs[formName].resetFields();
         },
         //编辑模态框
         handleEdit(index, row) {
            axios.get(`/admin/shop/categories/${row.id}`)
               .then((res) => {
                  this.dialogTableEdit = true;
                  this.category = res.data;
                  this.category.is_show = !!res.data.is_show;
               })
         },
         //更新
         updateForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  axios.put(`/admin/shop/categories/${this.category.id}`, this.category)
                     .then((res) => {
                        this.$message({
                           showClose: true,
                           message: '编辑分类成功',
                           type: 'success'
                        });
                        this.dialogTableEdit = false;
                        this.init();
                     })
               } else {
                  console.log('error submit!!');
                  return false;
               }
            });
         }
      }
   }
</script>

<style>
   .image {
      width: 80px;
      height: 30px;
      cursor: pointer;
   }
</style>